﻿using UnityEngine;
using System.Collections;

public class tileScript : MonoBehaviour {
	private string[] tileNames={"curve_piece1_A","curve_piece2_A","ramp_curve_piece1_B","ramp_curve_piece2_B","ramp_straight_piece_B","straight_piece_A", "double_piece"};
	private float[] angleAdjusters={90.0f,-90.0f,-90.0f,90.0f,0.0f,0.0f, 90.0f};
	public tileScript nextTile, nextTile2;
	public Transform _from,_tile,_to, _to2;
	public int whoAmI;
	public bool marbleOnMe;
	
	void Awake(){
		_from=transform.GetChild(0);
		_tile=_from.GetChild(0);
		_tile.gameObject.AddComponent<MeshCollider>();
        
		_to=_tile.GetChild(0);
        if (_tile.childCount > 1)
        {
            _to2 = _tile.GetChild(1);
        }
        marbleOnMe=false;
		nextTile=null;
	}
	
	void toColliderHit(){
		Debug.Log("to collider was hit");
		if(marbleOnMe)
			Destroy(gameObject,2.0f);
	}
	void fromColliderHit(GameObject source){
        print(source.transform.parent.name);
		Debug.Log("from collider was hit");
		marbleOnMe=true;
		tileScript T = nextTile;
        while (T.nextTile != null)
        {
            T = T.nextTile;
        }
		T.AddTiles(0);
        if (source.transform.parent.tag == "Double")
        {
            tileScript T2 = nextTile2;
            T.AddTiles(0);
            while (T2.nextTile != null)
                T2 = T2.nextTile;
            T2.AddTiles(0);
        }
			
	}
	
	public void AddTiles(int howManyMore){
        int who = Random.Range(0,7);//howManyMore;
		GameObject O=Instantiate(Resources.Load(tileNames[who])) as GameObject;
		tileScript T=O.GetComponent<tileScript>() as tileScript;
		nextTile=T;
		T.whoAmI=who;
		T._from.rotation=_to.rotation*Quaternion.Euler(0.0f,angleAdjusters[whoAmI],0.0f);
		T._from.position=_to.position;
        if (whoAmI == 6)
        {
            GameObject O2 = Instantiate(Resources.Load(tileNames[0])) as GameObject;
            tileScript T2 = O2.GetComponent<tileScript>() as tileScript;
            nextTile2 = T2;
            T2.whoAmI = 0;
            T2._from.rotation = _to2.rotation * Quaternion.Euler(0.0f, angleAdjusters[1], 0.0f);
            T2._from.position = _to2.position;
        }
		if(howManyMore>0)
			T.AddTiles(howManyMore-1);
	}
	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update () {
	
	}
}
